package com.eshin.autotest;

import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.Ordered;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;

/**
 * 对进行了PBEWithMD5AndDES加密的配置项进行解密
 *
 * @author Eshin
 */
public class CumstomPropertiesPropertySourceLoader implements PropertySourceLoader, Ordered {
    

    @Override
    public String[] getFileExtensions() {
        return new String[]{"properties", "xml", "conf"};
    }
    
    @Override
    public List<PropertySource<?>> load(String name, Resource resource)
            throws IOException {
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        Properties newProperties = new Properties();
        
        for (Entry<Object, Object> entry : properties.entrySet()) {
            String originalValue = (String) entry.getValue();
            originalValue = originalValue.trim();
            String oriKey = (String) entry.getKey();

            if(oriKey.equals("spring.cumstom.test")){
                originalValue = originalValue +"eshin cumstom";
            }
            newProperties.setProperty(oriKey, originalValue);

        }
        if (!newProperties.isEmpty()) {
            List<PropertySource<?>> list = new ArrayList<>();
            list.add(new PropertiesPropertySource(name, newProperties));
            return list;
        } else {
            return null;
        }
    }
    
    /**
     * 保证在多个loader匹配相同的getFileExtensions()时，最优先使用
     */
    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
